package com.noreply.timer.wx;

import com.alibaba.fastjson.JSONObject;
import com.noreply.timer.utils.ApplicationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author noreply
 * @description
 * @datetime 2021/9/2 19:55
 */
@Slf4j
public class WxApi {
    private static String accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET";

    private static String accessToken = null;

    private static int accessTokenExpireIn = 0;

    private static RestTemplate restTemplate = ApplicationUtil.applicationContext.getBean(RestTemplate.class);

    private static WxConfig wxConfig = ApplicationUtil.applicationContext.getBean(WxConfig.class);

    public static String getAccessToken() {
        String url = accessTokenUrl.replace("ID", wxConfig.getCorpId()).replace("SECRET", wxConfig.getSecret());
        ResponseEntity<JSONObject> result = restTemplate.getForEntity(url, JSONObject.class);
        if(result.getStatusCodeValue() == 0) {
            JSONObject body = result.getBody();
            if(body.getIntValue("errcode") == 0) {
                accessToken = body.getString("access_token");
                accessTokenExpireIn = body.getIntValue("expires_in");
            } else {
                log.error("get token error", JSONObject.toJSONString(result));
            }
        } else {
            log.error("get token error", JSONObject.toJSONString(result));
        }
        return accessToken;
    }
}
